import React, {useEffect, useState} from 'react';
import {Form, Button, DatePicker, TreeSelect, Upload, Input, Modal, Row, message, Col, Select} from 'antd';
import {connect} from 'umi';
import moment from 'moment';
import {UploadOutlined} from '@ant-design/icons';
import {getUploadUrl} from '@/utils/upload';
import SelectUserModal from "@/pages/components/SelectUserModal";
import {SearchOutlined} from '@ant-design/icons';
import {getShiftFrequency} from '../../service'

const FormItem = Form.Item;
const {TextArea} = Input;
const {Option} = Select;

const formLayout = {
  labelCol: {span: 7},
};

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};

let uploadedFiles = [];
const ShiftAddForm = (props) => {
  const {onSubmit, onCancel, loading, visible, currentUser, record, title, global = {}} = props;
  const {options = {}} = global;
  const {jobLevel = []} = options;
  const [form] = Form.useForm();
  const [fileUploadUrls, setFileUploadUrls] = useState([]);
  const [fileName, setFileName] = useState(null);
  const [userModalVisible, setUserModalVisible] = useState(false);
  const [selectType, setSelectType] = useState(null);
  const [info, setInfo] = useState({});
  const [shift, setShift] = useState([]);
  const [beShift, setBeShift] = useState([]);

  const fileList = {
    name: 'file',
    multiple: true,
    action: getUploadUrl(),
    data: {name: fileName},
    defaultFileList: uploadedFiles,
    beforeUpload(file) {
      setFileName(file.name)
    },
    onChange(res) {
      const {status} = res.file;
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`);
        } else {
          setFileUploadUrls([...fileUploadUrls, res.file.response]);
          message.success(`${res.file.name} 文件上传成功`);
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`);
      }
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.url);
      if (index > -1) {
        urls.splice(index, 1);
        setFileUploadUrls(urls);
      }
    },
  };

  useEffect(() => {
    if (currentUser) {
      if (record && visible) {
        initFrequency(record.shiftOid, record.beShiftOid, moment(record.shiftDate).format('YYYY-MM-DD'));
        setInfo({
          beShiftOid: record.beShiftOid,
          beShiftName: record.beShiftName,
          shiftOid: record.shiftOid,
          shiftName: record.shiftName
        });
        form.setFieldsValue({...record, shiftDate: moment(record.shiftDate)});
        setFileUploadUrls(record.fileUrl.split(','));
        if (record.fileUrl) {
          let fileList = record.fileUrl.split(',');
          fileList.forEach((item, index) => {
            uploadedFiles.push({
              uid: index,
              name: item.split('----')[1],
              status: 'done',
              url: item,
            })
          });
        }
      } else {
        form.setFieldsValue({
          applyCode: currentUser.usercode, applyOrgName: currentUser.orgname,
          applyName: currentUser.name, applyUnitName: currentUser.department, applyJobName: currentUser.jobname
        });
      }
    }
  }, [visible]);

  const onFormCancel = () => {
    form.resetFields();
    onCancel();
    setInfo({});
    uploadedFiles = [];
    setFileUploadUrls([]);
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    form.resetFields();
    onSubmit({
      ...fieldsValue,
      beShiftOid: info.beShiftOid,
      shiftOid: info.shiftOid,
      fileUrlList: fileUploadUrls,
      id: record && record.id
    });
    setInfo({});
    uploadedFiles = [];
    setFileUploadUrls([]);
  };

  const showUserModal = (type) => {
    setUserModalVisible(true);
    setSelectType(type);
  };

  const initFrequency = (shiftOid, beShiftOid, dateStr) => {
    let params = {shiftDate: dateStr, shiftOid, beShiftOid};
    getShiftFrequency(params).then(res => {
      if (res) {
        setBeShift(res.beFrequencyList);
        setShift(res.frequencyList);
      }
    })
  };

  const confirmSelectUser = (usersInfo) => {
    if (usersInfo.length > 0) {
      let data = {...info};
      let newFormValues;
      let userInfo = usersInfo[0];
      userInfo.jobLevel = userInfo.jobLevelId ? jobLevel.find(item => item.id === userInfo.jobLevelId)?.name : '';
      if (selectType === 'shift') {
        data.shiftName = userInfo.name;
        data.shiftOid = userInfo.oid;
        newFormValues = {
          shiftName: userInfo.name,
          shiftCode: userInfo.code,
          shiftOrgName: userInfo.orgname,
          shiftUnitName: userInfo.unitname,
          shiftJobName: userInfo.jobname,
        };
      } else {
        data.beShiftName = userInfo.name;
        data.beShiftOid = userInfo.oid;
        newFormValues = {
          beShiftName: userInfo.name,
          beShiftCode: userInfo.code,
          beShiftOrgName: userInfo.orgname,
          beShiftUnitName: userInfo.unitname,
          beShiftJobName: userInfo.jobname,
        };
      }
      if (data.beShiftOid === data.shiftOid){
        message.error('调班人与被调班人不能相同!');
        return;
      }
      form.setFieldsValue(newFormValues);
      setInfo(data);
      setUserModalVisible(false);
    } else {
      message.error('请选择人员!')
    }
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="applyCode" label="申请人工号">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="applyName" label="申请人">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="applyOrgName" label="公司">
              <TreeSelect disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="applyUnitName" label="部门">
              <TreeSelect disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="applyJobName" label="岗位">
              <Input disabled={true}/>
            </FormItem>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col {...colStyle}>
            <Form.Item label="调班人" name='shiftName' rules={[{required: true, message: '请选择人员！'}]}>
              <Input.Group compact size="large">
                <Input style={{width: '80%', height: '32px', fontSize: '14px', background: '#ffffff'}}
                       placeholder="选择人员" value={info ? info.shiftName : ''} disabled={true}/>
                <Button style={{width: '20%'}} icon={<SearchOutlined/>} onClick={() => showUserModal('shift')}/>
              </Input.Group>
            </Form.Item>
          </Col>
          <Col {...colStyle}>
            <FormItem name="shiftCode" label="调班人工号">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="shiftOrgName" label="调班人公司">
              <TreeSelect disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="shiftUnitName" label="调班人部门">
              <TreeSelect disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="shiftJobName" label="调班人岗位">
              <Input disabled={true}/>
            </FormItem>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col {...colStyle}>
            <Form.Item label="被调班人" name='beShiftName' rules={[{required: true, message: '请选择人员！'}]}>
              <Input.Group compact size="large">
                <Input style={{width: '80%', height: '32px', fontSize: '14px', background: '#ffffff'}}
                       placeholder="选择人员" value={info ? info.beShiftName : ''} disabled={true}/>
                <Button style={{width: '20%'}} icon={<SearchOutlined/>} onClick={() => showUserModal('beShift')}/>
              </Input.Group>
            </Form.Item>
          </Col>
          <Col {...colStyle}>
            <FormItem name="beShiftCode" label="被调班人工号">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="beShiftOrgName" label="被调班人公司">
              <TreeSelect disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="beShiftUnitName" label="被调班人部门">
              <TreeSelect disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="beShiftJobName" label="被调班人岗位">
              <Input disabled={true}/>
            </FormItem>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="shiftDate" label="调班时间" rules={[{required: true, message: '调班时间不能为空'}]}>
              <DatePicker placeholder="请选择调班时间" onChange={(date, dateStr) => initFrequency(info.shiftOid,info.beShiftOid,dateStr)}
                          className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="frequency" label="调班人班次" rules={[{required: true, message: '调班人班次不能为空'}]}>
              <Select placeholder="请选择调班班次">
                {shift.map((item, index) => {
                  return (
                    <Option value={item.id} key={index}>
                      {item.name}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="beFrequency" label="被调班人班次" rules={[{required: true, message: '被调班人班次不能为空'}]}>
              <Select placeholder="请选择被调班人班次">
                {beShift.map((item, index) => {
                  return (
                    <Option value={item.id} key={index}>
                      {item.name}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="fileUrl" label="上传附件">
              <Upload {...fileList}>
                <Button>
                  <UploadOutlined/> 点击上传附件
                </Button>
              </Upload>
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem name="reason" labelCol={{span: 2}} label="原因说明" rules={[{required: true, message: '原因说明不能为空'}]}>
              <TextArea rows={4} className='widthStyle'/>
            </FormItem>
          </Col>
        </Row>
      </>
    )
  };

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button type="primary" onClick={() => handleSubmit()} loading={loading}>提交</Button>
      </>
    )
  };

  return (
    <Modal
      width={1280}
      destroyOnClose
      centered
      title={`调班` + title}
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{paddingTop: '24px'}}
      >
        {renderContent()}
      </Form>
      <SelectUserModal
        selectType={0}
        visible={userModalVisible}
        handleOk={confirmSelectUser}
        handleCancel={() => setUserModalVisible(false)}
      />
    </Modal>
  )
};

export default connect(({user, global}) => ({
  currentUser: user.currentUser,
  global
}))(ShiftAddForm)
